<template>
  <div class="day9 colum-flex">
    <div class="range-container">
      <input type="range" id="range" min="0" max="100" @input="changeVal" v-model="numNow">
      <label :style="{left:labelX+'px'}" ref="$label">{{numNow}}</label>
    </div>
    <div class="tips">
      <div class="my-tip">string转num的便捷方式+'11' -> 11 </div>
      <b>**注意控制位置时 由于进度圆球宽24px的原因，想一直让标签与圆球中心对应的微调方案</b>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
const $label = ref(null)
const numNow = ref(0), labelX = ref(0)
function changeVal(e) {
  numNow.value = +e.target.value//转成数字
  let range_width = getComputedStyle(e.target).width//上下这两种效果一样
  let label_width = getComputedStyle($label.value).getPropertyValue('width')
  // range_width这俩得到的值是带px的 下面转成数字
  range_width = +range_width.substring(0, range_width.length - 2)
  label_width = +label_width.substring(0, label_width.length - 2)

  const max = +e.target.max
  const min = +e.target.min
  //----------------value/max * num_width//左边缘与进度条当前位置对齐
  //-------------------------------------------//往左再移label的一半  此时label中轴与进度圆左边缘对齐
  //-------------最容易忽略的部分-----------//进度条上的圆，宽度24，最左侧时 应当向右移12px 最右侧时应当向左移12px
  labelX.value = range_width * numNow.value / max - label_width / 2 + scale(numNow.value, min, max, 12, -12)
}

function scale(num, in_min, in_max, out_min, out_max) {
  return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

onMounted(() => {
  labelX.value = - getComputedStyle($label.value).width.split('px')[0] / 2 + 12//12是对中轴对应圆球中心做补偿
})
</script>

<style lang="scss">
.day9 {
  background-color: #ecf0f1;

  .range-container {
    position: relative;
  }

  input {
    width: 300px;
    margin: 18px 0;
    -webkit-appearance: none;

    &::-webkit-slider-runnable-track {
      background: purple;
      border-radius: 4px;
      width: 100%;
      height: 10px;
      cursor: pointer;
    }

    &::-webkit-slider-thumb {
      -webkit-appearance: none;
      height: 24px;
      width: 24px;
      background: #fff;
      border-radius: 50%;
      border: 1px solid purple;
      margin-top: -7px;
      cursor: pointer;
    }
  }

  input:focus {
    outline: none;
  }

  input+label {
    background-color: #fff;
    position: absolute;
    top: -30px;
    // left: 110px;
    width: 80px;
    padding: 5px 0;
    text-align: center;
    border-radius: 4px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
  }
}
</style>